<template>
  <div class="meida">
    <a-form-model ref="ruleForm" :rules="rules" :model="ruleForm">
      <a-row justify="space-between">
        <a-col :span="8">
          <a-form-model-item has-feedback label="名称" prop="appName" :labelCol="{ span: 2 }" :wrapperCol="{ span: 18, offset: 1 }">
            <a-input v-model="ruleForm.appName" allow-clear placeholder="请输入" />
          </a-form-model-item>
        </a-col>
        <!--         <a-col :span="8">
          <a-form-model-item has-feedback label="状态" prop="partnership" :labelCol="{ span: 3 }" :wrapperCol="{ span: 18, offset: 1 }">
            <a-select v-model="ruleForm.partnership" :defaultValue="0">
              <a-select-option :value="0">
                全部状态
              </a-select-option>
              <a-select-option :value="1">
                合作中
              </a-select-option>
              <a-select-option :value="2">
                已暂停
              </a-select-option>
              <a-select-option :value="3">
                未合作
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col> -->
        <a-col :span="10" push="14">
          <a-form-model-item>
            <a-space>
              <a-button @click="resetForm">
                重置
              </a-button>
              <a-button :loading="tableLoading" type="primary" @click="submitForm('ruleForm')">
                查询
              </a-button>
            </a-space>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-row class="details" justify="space-between">
      <a-col :span="8">
        <h3>详情列表</h3>
      </a-col>
      <a-col :span="8" offset="8" push="5">
        <a-button class="newBuild" type="primary" icon="plus" @click="handleAddMedia('新建媒体')">
          新建媒体
        </a-button>
        <util-modules @refresh="refreshData" @densityChange="densityChange" />
      </a-col>
    </a-row>

    <a-table
      :loading="tableLoading"
      :pagination="false"
      :bordered="false"
      :columns="columns"
      :data-source="data"
      :rowKey="(record) => record.appKey"
      @change="handleTableChange"
      :size="activeSize"
    >
      <span slot="appName" slot-scope="_, record">
        <a>{{ record.appName || '-' }}</a>
      </span>
      <span slot="slotCount" slot-scope="_, record">
        <a @click="handleToAdverIndex(record)">{{ record.slotCount }}</a>
      </span>
      <span slot="status" slot-scope="_, record">
        <a-badge v-if="record.partnership == 1" status="processing" text="合作中" />
        <a-badge v-if="record.partnership == 2" status="error" text="已暂停" />
        <a-badge v-if="record.partnership == 3" status="default" text="未合作" />
      </span>
      <span slot="action" slot-scope="_, record">
        <a @click="handleAddMedia('媒体设置', record)">编辑</a>
        <a-divider type="vertical" />
        <a @click="viewData(record)">查看数据</a>
      </span>
    </a-table>
    <a-row class="pagination">
      <!-- 第${range[0]} - ${range[1]}条/ -->
      <a-pagination
        show-size-changer
        :default-current="pageNo"
        :total="total"
        :defaultPageSize="100"
        :show-total="(total, range) => `总共${total}条`"
        show-less-items
        :page-size-options="['10', '20', '50', '100']"
        @change="handleCurrentChange"
        @showSizeChange="handleSizeChange"
      />
    </a-row>

    <!-- model in from -->
    <!-- 新建模态框 -->
    <a-modal v-model="visible" :title="motaiTitle" on-ok="handleOk">
      <el-form size="small" ref="compileFormRef" :model="compileFormRef" label-width="80px">
        <el-form-item label="媒体名称:">
          <el-input class="inputBox" v-model="compileFormRef.appName"></el-input>
        </el-form-item>
        <el-form-item label="媒体账户:">
          <el-select class="selectBox" v-model="compileFormRef.subUserId" placeholder="请选择">
            <el-option label="请选择" value="0"></el-option>
            <el-option v-for="item in seleteDateArr" :key="item.id" :label="item.username" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合作设置:">
          <el-radio-group v-model="compileFormRef.partnership">
            <el-radio :label="1">合作</el-radio>
            <el-radio :label="2">暂停合作</el-radio>
            <el-radio :label="3">未合作</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <a-button key="back" @click="handleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
          保存
        </a-button>
      </template>
    </a-modal>
    <!-- model in end -->
  </div>
</template>

<script>
import { columns } from '@/mock/table/table'
import UtilModules from '_c/UtilModules.vue'
import { getTableSize } from '@/lib/utils'
import { getAppList, postAppUpdate, getSubUserChildList } from '@/api/MeidaMan/api'
export default {
  name: 'media',
  components: {
    UtilModules,
  },
  data() {
    return {
      activeSize: '',
      loading: false,
      tableLoading: false,
      visible: false,
      ruleForm: {
        appName: '',
        partnership: 1,
      },
      rules: {},
      columns,
      data: [],
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'media' }),
      // 分页
      pageNo: 1,
      pageSize: 100,
      total: 0,
      tableSize: 'mini',
      // 模态框
      motaiTitle: '', // 模态框title
      seleteDateArr: [],
      compileFormRef: {
        appName: '',
        subUserId: '0',
        partnership: 1,
      },
    }
  },
  created() {},
  mounted() {
    this.appList(this.pageNo, this.pageSize)
  },
  computed: {},
  methods: {
    /**
     * @func 刷新数据
     */
    refreshData() {
      this.appList(this.pageNo, this.pageSize)
    },
    /**
     * @func 表格密度
     */
    densityChange(value) {
      const { tableSize } = this.$store.state
      this.activeSize = getTableSize(value, tableSize)
    },
    /**
     * @func 表格变化时
     */
    async handleTableChange(_, filters) {
      const arr = filters.status
      const { appName } = this.ruleForm
      const partnership = arr.toString() || '1'
      this.ruleForm.partnership = partnership
      this.appList(this.pageNo, this.pageSize, appName, partnership)
    },
    /**
     * @func 跳转至广告位
     */
    handleToAdverIndex(record) {
      const { appKey } = record
      this.$router.push(`/advertising?appKey=${appKey}`)
    },
    /**
     * @func 列表数据
     */
    appList(pageNo, pageSize, appName, partnership) {
      this.tableLoading = true
      getAppList({ pageNo, pageSize, appName, partnership })
        .then((res) => {
          this.total = res.data.data.count
          this.data = res.data?.data?.list ?? []
          this.tableLoading = false
        })
        .catch((err) => {
          this.tableLoading = false
          this.$msgErr(err)
        })
    },

    /**
     *  @func 改变页面值
     */
    handleCurrentChange(page, pageSize) {
      console.log(page)
      this.pageNo = page
      this.pageSize = pageSize
      const { appName } = this.ruleForm
      this.appList(this.pageNo, this.pageSize, appName)
    },

    /**
     *  @func 改变页面数据多少
     */
    handleSizeChange(current, size) {
      this.pageNo = current
      this.pageSize = size
      const { appName } = this.ruleForm
      this.appList(this.pageNo, this.pageSize, appName)
    },
    /**
     * 刷新
     */
    refresh() {
      console.log('刷新')
      // this.pageSize = 10
      // this.pageNo = 1
      this.ruleForm.values = ''
      this.tableLoading = true
      const { appName } = this.ruleForm
      this.appList(this.pageNo, this.pageSize, appName)
    },
    /**
     * @func 新增或修改应用
     */
    async appUpdate(param) {
      this.loading = true
      try {
        await postAppUpdate(param)
        this.$msgSuc('成功')
        // 重新渲染页面
        this.pageNo = 1
        this.pageSize = 100
        this.appName = ''
        const { appName, partnership } = this.ruleForm
        this.appList(this.pageNo, this.pageSize, appName, partnership)
        this.visible = false
        this.loading = false
      } catch (err) {
        this.visible = false
        this.loading = false
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 查询按钮数据
     */
    submitForm() {
      this.pageNo = 1
      this.pageSize = 100
      const { appName, partnership } = this.ruleForm
      this.appList(this.pageNo, this.pageSize, appName, partnership)
    },
    /**
     * @func 重置按钮表单
     */
    resetForm() {
      this.appList()
      this.$refs.ruleForm.resetFields()
    },
    /**
     * @func 打开新建模态框
     */
    handleAddMedia(title, record) {
      console.log(record)
      if (title === '新建媒体') {
        console.log('新建媒体')
        this.compileFormRef.appName = ''
        this.compileFormRef.subUserId = '0'
        this.compileFormRef.partnership = 1
        delete this.compileFormRef.appKey
      } else if (title === '媒体设置') {
        this.compileFormRef.appKey = record.appKey
        this.compileFormRef.appName = record.appName
        this.compileFormRef.subUserId = record.subUserId
        this.compileFormRef.partnership = record.partnership
      }
      this.motaiTitle = title
      this.visible = true
      this.queryAccount()
    },
    /**
     * @func 新建模态框
     * @desc 保存
     */
    handleOk(e) {
      e.preventDefault()
      console.log(this.compileFormRef)
      if (this.compileFormRef.appName.length < 1) {
        return this.$msgErr('添加失败,请重试!')
      }
      this.appUpdate(this.compileFormRef)
    },
    /**
     * @func 新建模态框
     * @desc 取消
     */
    handleCancel(e) {
      this.visible = false
    },
    /**
     * @func 查询媒体账户
     */
    async queryAccount() {
      try {
        const data = await getSubUserChildList()
        if (data) {
          console.log(data)
          data.forEach((item) => {
            item.username = `${item.username}[${item.userDesc}]`
          })
          this.seleteDateArr = data
        }
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 查看数据
     */
    viewData(record) {
      this.$router.push(`/media-data?appKey=${record.appKey}`)
    },
  },
}
</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  display: flex;
  flex-direction: row;
}
.details {
  margin-bottom: 20px;
}
::v-deep .pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
// 图标按钮
.ant-btn-icon-only {
  border: 0;
  margin: 0 5px;
}
.newBuild {
  margin-left: 10px;
  margin-right: 5px;
}
.inputBox {
  width: 70%;
}
.selectBox {
  width: 70%;
}
</style>
